package common

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha1"
	"encoding/base64"
	b64 "encoding/base64"
	"encoding/hex"
	"fmt"
	"io"
)

// SSHHash 和SSH known_hosts中的hash算法相同
func SSHHash(salt string, data string) string {
	return Base64Encode(Sha1(salt, data))

}

// Sha1 use hmac
func Sha1(salt string, data string) []byte {

	base64Salt, err := Base64Decode(salt)
	if err != nil {
		fmt.Println(err)
	}

	hash := hmac.New(sha1.New, base64Salt)

	if _, err := io.WriteString(hash, data); err != nil {
		fmt.Println(err)
	}

	bs := hash.Sum(nil)
	return bs
}

// Base64Encode base64 encode
func Base64Encode(data []byte) string {
	return b64.StdEncoding.EncodeToString(data)
}

// Base64Decode base64 decode
func Base64Decode(data string) ([]byte, error) {
	return b64.StdEncoding.DecodeString(data)
}

// Generate a salt string with 16 bytes of crypto/rand data.
func generateSalt() string {
	randomBytes := make([]byte, 16)
	_, err := rand.Read(randomBytes)
	if err != nil {
		return ""
	}
	return base64.URLEncoding.EncodeToString(randomBytes)
}

// hexEncode convert byte to the value string
func hexEncode(data []byte) string {
	return hex.EncodeToString(data)
}
